<!--
  - Copyright (c) 2021.  北京维数科技有限公司
  - Date :  2021/3/25
  - Author ：F12 Console=> atob("MzMxNDkxODAwQHFxLmNvbQ==")
  - Version ：1.0.0
  -->

<template>
  <div><div class="abstatic-height"></div>
  <div class="app-container calendar-list-container">
    <el-row>
      <div class="xf-tabletop-handles">
        <div class="xf-tabhd-left">
          <el-button
            class="filter-item"
            @click="handleCreate"
            type="primary"
            icon="edit" size="mini">
          添加用户</el-button>
        </div>
        <div class="xf-tabhd-right">
          用户名
          <el-input @keyup.enter.native="handleFilter" class="xf-query-input" v-model="listQuery.username" size="mini">
          </el-input>
          <el-button class="filter-item" type="primary" icon="search" :disabled="isadvance" @click="handleFilter" size="mini">查询</el-button>
          <el-popover
          placement="bottom"
          width="400"
          v-model="isadvance"
          trigger="click">
          <div class="advancesearch" :class="{adminsearch:adminid==1}">
            <el-form :label-position="labelPosition" label-width="80px" :model="formLabelAlign" ref="searchForm" :rules="advancerules" @submit.native.prevent>
              <el-form-item label="角色" style="margin-top: 20px;" v-if="adminid!=1">
                <el-select v-model="formLabelAlign.groupId" placeholder="全部" style="width: 100%;">
                  <el-option label="全部" value=""></el-option>
                  <el-option :label="item.name" :value="item.id" v-for="(item,index) in grouplist" :key="index"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="真实姓名" prop="name">
                <el-input v-model.trim="formLabelAlign.name"></el-input>
              </el-form-item>
              <el-form-item label="手机号" prop="mobilePhone">
                <el-input v-model.number="formLabelAlign.mobilePhone"></el-input>
              </el-form-item>
              <el-button type="primary" @click="handleAdvaceSerach('searchForm')" size="mini" native-type="submit">查询</el-button>
              <el-button type="text" @click="isadvance=false;">取消</el-button>
            </el-form>
          </div>
          <el-button class="filter-item" slot="reference" @click.stop="isadvance=true" type="text" size="mini">高级查询</el-button>
          </el-popover>
        </div>
      </div>
    </el-row>
    <el-table ref="multipleTable" :key='tableKey' :data="list" v-loading.body="listLoading" style="width: 100%;"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column  label="用户名">
        <template slot-scope="scope">
          <span>{{scope.row.username}}</span>
        </template>
      </el-table-column>
      <el-table-column  label="真实姓名">
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column  label="手机号">
        <template slot-scope="scope">
          <span>{{scope.row.mobilePhone}}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色" v-if="adminid!=1">
        <template slot-scope="scope">
          <span>{{scope.row.role}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="150">
        <template slot-scope="scope">
          <span @click="handleUpdate(scope.row)" class="comm-table-btn"><icon-svg icon-class="bianji" style="fill:#50E3C2" /></span>
          <span @click="handleDelete(scope.row)" class="comm-table-btn"><icon-svg icon-class="shanchu" style="fill:#50E3C2" /></span>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container" style="margin-top: 10px;">
      <el-checkbox v-model="isAllcheck" @change="handleCheckAllChange" :indeterminate="isIndeterminate" v-show="list.length!=0">全选</el-checkbox>
      <el-button type="text" style="margin-left: 14px;" @click="handleDelUsers" v-show="list.length!=0" :disabled="checklist.length==0">删除用户</el-button>
      <el-pagination style="float:right;" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page"
        :page-sizes="[15,30,45, 60]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <slider-panel :Show.sync="isadduser" custom-class="out-side-frame">
      <div class="form-content-frame">
        <el-form :label-position="labelPosition" ref="userInfoForm" label-width="80px" :model="userinfo" :rules="userrules" @submit.native.prevent>
        <el-form-item label="用户名" prop="username">
          <el-input v-model.trim="userinfo.username" :disabled="dialogStatus=='create'?false:true"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="name">
          <el-input v-model.trim="userinfo.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobilePhone">
          <el-input v-model.trim="userinfo.mobilePhone"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="groupId" v-if="adminid!=1">
          <el-select v-model="userinfo.groupId" style="width: 100%;">
            <el-option :label="item.name" :value="item.id" v-for="(item,index) in grouplist" :key="index">{{item.name}}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogStatus=='create'">
          <el-input v-model.trim="userinfo.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="repass" v-if="dialogStatus=='create'">
          <el-input v-model.trim="userinfo.repass" type="password"></el-input>
        </el-form-item>
            <el-button v-if="dialogStatus=='create'" type="primary" @click="create('userInfoForm')" size="mini" native-type="submit">确 定</el-button>
            <el-button v-else type="primary" @click="update('userInfoForm')" size="mini" native-type="submit">确 定</el-button>
            <el-button @click="cancel('userInfoForm')" type="text" size="mini">取 消</el-button>
      </el-form>

      </div>
    </slider-panel>
    <el-dialog title="删除用户" :visible.sync="dialogDeleteVisible" :show-close='false' custom-class="xf-jc-dialog" width="360px" height="160px">
      <div class="xf-jc-deletect">
        <p>{{delusertext}}</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" size="mini" @click="deluser">删除</el-button>
        <el-button size="mini" @click="dialogDeleteVisible=false;deluserinfo.id.length=0;">取消</el-button>
      </div>
    </el-dialog>
  </div>
  </div>
</template>

<script>
import { randomn } from "@/utils";
import {
  page,
  addObj,
  getObj,
  delObj,
  updateObj,
  getGroup,
  getUserRole
} from '@/api/admin/user/index';
import { getTypeValue } from '@/api/dict/dictValue/index';
import { mapGetters } from 'vuex';
import sliderPanel from '@/components/SliderPanel'
export default {
  name: 'user',
  components: {
    'depart-selector': () => import('./components/departSelector'),
    sliderPanel
  },
  data() {
    return {
      form: {
        username: undefined,
        name: undefined,
        password: undefined,
        description: undefined,
        departName: undefined,
        departId: undefined
      },
      labelPosition: 'top',
      formLabelAlign: {
        groupId:"",
        username: '',
        mobilePhone: ''
      },
      advancerules:{
        name:{
          max: 50,
          message: '长度在50个字符以内',
          trigger: 'blur'
        },
        mobilePhone:[
          {validator:(rule, value, callback)=>{
            let myreg=/^[1][3,4,5,7,8][0-9]{9}$/;
            if (value!=="") {
              if (!myreg.test(value)&&value.length!=11) {
                callback(new Error('请输入正确的手机号!'))
              }else{
                callback();
              }
            }else{
              callback();
            }
          },trigger:'blur'}
        ]
      },
      userrules: {
        username: [
          {
            required: true,
            message: '请输入用户',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 50,
            message: '长度在3到50个字符以内',
            trigger: 'blur'
          },
          {validator:(rule, value, callback)=>{
            let patrn = /[^\w\.\/]/ig;
            if (patrn.test(value)) {
              callback(new Error('用户名只能为数字和字母!'))
            }else{
              callback();
            }
          },trigger:'blur'}
        ],
        name: [
          {
            max: 50,
            message: '长度在50个字符以内',
            trigger: 'blur'
          }
        ],
        mobilePhone: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {validator:(rule, value, callback)=>{
            let myreg=/^[1][3,4,5,7,8][0-9]{9}$/;
            if (!myreg.test(value)&&value.length!=11) {
              callback(new Error('请输入正确的手机号!'))
            }else{
              callback();
            }
          },trigger:'blur'}
        ],
        groupId: [
          {
            required: true,
            message: '请选择角色',
            trigger: 'blur'
          }
        ],
        password:[
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {validator:(rule, value, callback)=>{
            if (value.length<6||value.length>18) {
              callback(new Error('请设置6-18位密码!'))
            }else{
              callback();
            }
          },trigger:'blur'}
        ],
        repass:[
          {
            required: true,
            message: '请输入确认密码',
            trigger: 'blur'
          },
          {validator:(rule, value, callback)=>{
            if (value.length<6||value.length>18) {
              callback(new Error('请设置6-18位密码!'))
            }else if(value!=this.userinfo.password){
              callback(new Error('两次输入密码不一致!'))
            }else{
              callback();
            }
          },trigger:'blur'}
        ]
      },
      list: [],
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 15,
        username: undefined,
        name:undefined,
        groupId: undefined,
        mobilePhone:undefined
      },
      dialogFormVisible: false,
      dialogDepartVisible: false,
      dialogStatus: '',
      userManager_btn_edit: false,
      userManager_btn_del: false,
      userManager_btn_add: false,
      textMap: {
        update: '编辑',
        create: '创建'
      },
      tableKey: 0,
      isadvance:false,
      isadduser:false,
      userinfo:{
        name:"",
        username:"",
        mobilePhone:"",
        groupId:"",
        password:"",
        repass:"",
      },
      grouplist:[],
      dialogDeleteVisible:false,
      delusertext:"",
      deluserinfo:{
        id:[],
        name:"",
        index:0,
      },
      isAllcheck:false,
      checklist:[],
      isIndeterminate:false,
    }
  },
  created() {
    this.getList();
    this.getGroupList();
  },
  computed: {
    ...mapGetters([
      'elements',
      'adminid',
    ])
  },
  methods: {
    getList() {
      this.listLoading = true;
      page(this.listQuery)
        .then(response => {
          this.list = response.data.rows;
          this.total = response.data.total;
          this.listLoading = false;
        })
    },
    getGroupList(){
      getGroup().then((res)=>{
        res.forEach((item,index)=>{
          this.grouplist.push({
            id:item.id,
            name:item.name
          });
        })
      })
    },
    searchrole(data){
      data.forEach((item,index)=>{
          if (item.isUser==1) {
            this.userinfo.groupId=item.id;
          }
      })
    },
    handleFilter() {
      if (this.listQuery.username=="") {
        this.listQuery.username = undefined
      };
      this.resetlist()
      this.getList();
    },
    resetlist(){
      this.listQuery.groupId=undefined;
      this.listQuery.name=undefined;
      this.listQuery.mobilePhone=undefined;
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = 'create';
      this.isadduser = true;
    },
    handleUpdate(row) {
      getObj(row.id)
        .then(response => {
          try {
          this.userinfo.username = response.data.username;
          this.userinfo.name = response.data.name;
          this.userinfo.mobilePhone = response.data.mobilePhone;
          getUserRole({userId:row.id}).then(res=>{
              this.searchrole(res.data);
          })
          } catch (e) {
            console.log('error：部门转化json失败' + e);
          }
          this.isadduser = true;
          this.dialogStatus = 'update';
        });
    },
    handleDelete(row) {
      this.delusertext=`确定删除“${row.username}”吗？`;
      this.dialogDeleteVisible=true;
      this.deluserinfo.id.length=0;
      this.deluserinfo.id.push(row.id);
      this.deluserinfo.name=row.name;
      const index = this.list.indexOf(row);
      this.deluserinfo.index=index;
    },
    deluser(){
      delObj({userIds:this.deluserinfo.id.toString()})
      .then((res) => {
        if (res.status==200) {
            this.dialogDeleteVisible = false;
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            });
            this.list.splice(this.deluserinfo.index, 1);
            this.getList();
        }else{
           this.$notify({
              title: '失败',
              message: res.data.message,
              type: 'warning',
              duration: 2000
            }).then(()=>{
            })
        }
        this.isAllcheck=false;
      });
      this.dialogDeleteVisible = false;
    },
    handlerAddDepart() {
      this.$refs.departSelector.onSubmit()
    },
    create(formName) {
      const set = this.$refs;
      set[formName].validate((valid) => {
        if (valid) {
          this.userinfo.password = window.btoa(window.btoa(this.userinfo.password) + randomn(7))
          this.userinfo.repass = window.btoa(window.btoa(this.userinfo.repass) + randomn(7))
          addObj(this.$qs.stringify(this.userinfo))
            .then((response) => {
              if (response.status==200) {
                this.isadduser = false;
                this.getList();
                this.$notify({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                });
                set[formName].resetFields();
              }else{
                this.$notify({
                  title: '提示',
                  message: response.message,
                  type: 'warning',
                  duration: 2000
                });
                set[formName].resetFields();
              }
            })
        } else {
          return false;
        }
      });
    },
    cancel(formName) {
      this.isadduser = false;
      this.$refs[formName].resetFields();
    },
    cancelSerch(formName){
      this.isadvance = false;
      this.$refs[formName].resetFields();
    },
    update(formName) {
      const set = this.$refs;
      set[formName].validate(valid => {
        if (valid) {
          updateObj(this.$qs.stringify(this.userinfo)).then((res) => {
            if (res.status==200) {
              this.isadduser = false;
              this.getList();
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              });
            }else{
              this.isadduser = false;
              this.getList();
              this.$notify({
                title: '提示',
                message: res.message,
                type: 'warning',
                duration: 2000
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    openDepartDialog() {
      this.dialogDepartVisible = true
    },
    closeDepartDialog(depart) {
      this.form.departName = depart.label
      this.form.departId = depart.id
      this.dialogDepartVisible = false
    },
    resetTemp() {
      for(let i in this.userinfo){
        this.userinfo[i]="";
      }
    },
    handleSelectionChange(val){
      this.checklist=[...val];
      let length = this.total>this.list.length?this.list.length:this.total;
      if (val.length==length) {
        this.isAllcheck=true;
        this.isIndeterminate=false;
      }else{
        this.isAllcheck=false;
        this.isIndeterminate=true;
      }
      if (val.length==0) {
        this.isIndeterminate=false;
      }
    },
    handleCheckAllChange(){
        this.$refs.multipleTable.toggleAllSelection();
    },
    handleAdvaceSerach(formName){
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
          if (this.formLabelAlign.groupId!="") {
            this.listQuery.groupId=this.formLabelAlign.groupId;
          }else {
            this.listQuery.groupId=undefined;
          }
          if (this.formLabelAlign.name!="") {
            this.listQuery.name=this.formLabelAlign.name;
          }else {
            this.listQuery.name=undefined;
          }
          if (this.formLabelAlign.mobilePhone!="") {
            this.listQuery.mobilePhone=this.formLabelAlign.mobilePhone;
          }else{
            this.listQuery.mobilePhone=undefined
          }
          if (this.listQuery.username=="") {
            this.listQuery.username=undefined;
          }
          this.getList();
          this.isadvance=false;
        }
      });
    },
    handleDelUsers(){
      this.deluserinfo.id.length=0;
      if (this.checklist.length==0) {
         this.$notify({
            title: '提示',
            message: '请选择用户',
            type: 'warning',
            duration: 2000
          });
          return;
      }else if (this.checklist.length==1) {
        this.delusertext=`确定删除“${this.checklist[0].username}”吗？`;
      }else{
        this.delusertext=`确定要删除这${this.checklist.length}个用户吗？`;
      }
      this.checklist.forEach((item,index)=>{
          this.deluserinfo.id.push(item.id);
      });
      this.dialogDeleteVisible=true;
    },
  },
  mounted(){
    /*let self=this;
    document.onclick=function(){
      self.isadvance=false;
    }*/
  }
}
</script>
<style lang="scss">
  button:-moz-focusring, [type="button"]:-moz-focusring, [type="reset"]:-moz-focusring, [type="submit"]:-moz-focusring {
      outline: none;
  }
.xf-query-input,
.xf-query-select {
  width: 200px;
  margin: 0 10px;
}
  .advancesearch label{
    padding: 0 !important;
  }
  .roundbtn{
    width: 77px;
    height: 28px;
    line-height: 0;
  }
  .fulldialog > div {
  width: 500px;
  margin: 0 auto;
}
.fulldialog .el-dialog__title {
  font-size: 32px;
}
.fulldialog {
  .el-dialog__header {
    margin-top: 20px;
  }
  .custom-dialog-btn {
    position: absolute;
    font-size: 30px;
    left: 40px;
    top: 20px;
    color: #fff;
    &:hover {
      cursor: pointer;
    }
  }
  .dialog-footer {
    text-align: left;
  }
}
.xf-jc-dialog {
  margin-top:15vh !important;
}
.pagination-container .el-checkbox{
  margin-left:14px;
}
.adminsearch{
  height:250px;
}
</style>
</style>
